package com.itheima.wechatweb;

import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisConstant;
import com.itheima.entity.Result;
import com.itheima.entity.SmsResponse;
import com.itheima.utils.RedisUtil;
import com.itheima.utils.SmsUtil;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * @outhor
 * @date 2020/2/5 9:08
 */

@RequestMapping("validateCode")
@RestController
public class validateCodeController {

    @Autowired
    RedisUtil redisUtil;

    @RequestMapping("send4Order")
    public Result send4Order(@RequestBody Map map){
        try {
            String telephone = (String) map.get("telephone");
            String deviceId = (String) map.get("deviceId");
            String inputImgCode = (String) map.get("inputImgCode");
            if(null==deviceId){return new Result(false,"非法请求");}
            String redisImgCode = redisUtil.get(deviceId);
            redisUtil.delete(deviceId);
            if(redisImgCode ==null || redisImgCode.equals("") || !redisImgCode.equalsIgnoreCase(inputImgCode) ){return new Result(false,"验证码输入错误");}
            //1.生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(4);
            //2.使用阿里云工具发送短消息
//            SmsResponse smsResponse = SmsUtil.sendSmsCode(telephone,code.toString());
            //3.将验证码保存在redis中（用户提交预约时需要校验）注意：redis key = 手机号码 + 后缀（能代码当前业务）
            redisUtil.setex(telephone+RedisConstant.SENDTYPE_ORDER,code.toString(),20*60);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }

    @RequestMapping("send4Login")
    public Result send4Login(String telephone){
        try {
            //1.生成验证码
            Integer code = ValidateCodeUtils.generateValidateCode(6);
            //2.使用阿里云工具发送短消息
//            SmsResponse smsResponse = SmsUtil.sendSmsCode(telephone,code.toString());
            //3.将验证码保存在redis中（用户提交预约时需要校验）注意：redis key = 手机号码 + 后缀（能代码当前业务）
            redisUtil.setex(telephone+RedisConstant.SENDTYPE_LOGIN,code.toString(),20*60);
            return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
    }
}
